<template>
  <div class="app-container inden-manage sticky-box">
    <div>
      <avue-form
        :option="option"
        v-model="queryParams"
        ref="searchForm"
        v-show="showSearch"
        @keydown.enter="getList"
      >
        <!-- <template #customerId>
          <el-select
            class="w-full"
            v-model="queryParams.customerId"
            placeholder="请选择客户名称"
            @focus="selectCustomerFn('customerId')"
          >
            <el-option
              v-for="item in customerOption['customerId']"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            ></el-option>
          </el-select> -->
        <!-- <el-select
            v-model="queryParams.customerId"
            placeholder="请选择客户名称"
            class="w-full"
            filterable
            remote
            clearable
            :remote-method="queryCustomer"
            :loading="loadingSelect"
            no-data-text="未查询到客户"
          >
            <el-option
              v-for="item in parentOptions"
              :key="item.id"
              :label="item.customerName"
              :value="item.id"
            >
              <div>
                <span>{{ item.customerName }}</span>
              </div>
            </el-option>
          </el-select>
        </template> -->
        <template #menu-form>
          <el-button icon="Search" type="primary" @click="getList" class="m-l-3"
            >查询</el-button
          >
          <el-button icon="Refresh" @click="handleEmpty(searchForm)"
            >重置</el-button
          >
          <el-button icon="Filter" type="primary" @click="handleSearch" link
            >高级查询</el-button
          >
        </template>
      </avue-form>

      <el-drawer
        v-model="searchDrawer"
        title="高级检索"
        :show-close="false"
        size="40%"
      >
        <template #header="{ close, titleId, titleClass }">
          <h4 :id="titleId" :class="titleClass">高级检索</h4>
          <el-button
            class="search-drawer-retract"
            icon="ArrowRight"
            type="danger"
            @click="close"
            link
          >
            收起
          </el-button>
        </template>
        <avue-form
          :option="searchOption"
          v-model="queryParams"
          ref="seniorSearchForm"
          @keydown.enter="getList"
        >
          <!-- <template #customerId>
            <el-select
              v-model="queryParams.customerId"
              placeholder="请选择客户名称"
              class="w-full"
              filterable
              remote
              clearable
              :remote-method="queryCustomer"
              :loading="loadingSelect"
              no-data-text="未查询到客户"
            >
              <el-option
                v-for="item in parentOptions"
                :key="item.id"
                :label="item.customerName"
                :value="item.id"
              >
                <div>
                  <span>{{ item.customerName }}</span>
                </div>
              </el-option>
            </el-select>
            <el-select
              class="w-full"
              v-model="queryParams.customerId"
              placeholder="请选择客户名称"
              @focus="selectCustomerFn('customerId')"
            >
              <el-option
                v-for="item in customerOption['customerId']"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              ></el-option>
            </el-select>
          </template> -->
          <template #projectId>
            <el-select
              v-model="queryParams.projectId"
              placeholder="请选择关联项目"
              class="w-full"
              suffix-icon="Search"
              remote-show-suffix
              :suffix-transition="false"
              filterable
              remote
              clearable
              :remote-method="
                val => queryProjectLimitEnt(val, queryParams.customerId)
              "
              :loading="!projectOptionsLimitEnt"
            >
              <el-option
                v-for="item in projectOptionsLimitEnt"
                :key="item.projectId"
                :label="item.proName"
                :value="item.projectId"
              >
                <div>
                  <span>{{ item.proName }}</span>
                </div>
              </el-option>
            </el-select>
          </template>
          <template #contractId>
            <el-select
              v-model="queryParams.contractId"
              placeholder="请选择关联合同"
              class="w-full"
              suffix-icon="Search"
              remote-show-suffix
              :suffix-transition="false"
              filterable
              remote
              clearable
              :remote-method="
                val => queryContractLimitEnt(val, queryParams.customerId)
              "
              :loading="!contractOptionsLimitEnt"
            >
              <el-option
                v-for="item in contractOptionsLimitEnt"
                :key="item.rcId"
                :label="item.contractName"
                :value="item.rcId"
              >
                <div>
                  <span>{{ item.contractName }}</span>
                </div>
              </el-option>
            </el-select>
          </template>
          <template #menu-form>
            <div class="text-center">
              <el-button icon="Search" type="primary" @click="getList"
                >查询</el-button
              >
              <el-button icon="Refresh" @click="handleEmpty(searchForm)"
                >重置</el-button
              >
            </div>
          </template>
        </avue-form>
      </el-drawer>

      <el-row :gutter="10" class="mb4">
        <el-col :span="1.5">
          <el-button type="primary" icon="Plus" @click="handleAdd"
            >新增</el-button
          >
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button type="info" plain icon="Download" @click="handleDownload"
            >导出数据</el-button
          >
        </el-col> -->
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="EditPen"
            @click="handleUpdate"
            :disabled="disUpdate"
            >编辑订单</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="RemoveFilled"
            plain
            @click="handleStop"
            :disabled="disUpdate || stopBtn"
            >关闭订单</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="RemoveFilled"
            v-hasPermi="['sales:salesOrder:export']"
            plain
            @click="exportFile"
            >导出</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="Upload"
            plain
            @click="
              () => {
                uploadDia.open = true
              }
            "
            >导入</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="RemoveFilled"
            plain
            v-hasPermi="['sales:salesOrder:remove']"
            @click="handleReview"
            >自动审核配置</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="Star"
            plain
            v-hasPermi="['sales:salesOrder:limits']"
            @click="authoritySetting"
            >权限设置</el-button
          >
        </el-col>

        <el-col :span="1.5"
          ><!-- .status !== '5' -->
          <el-button
            type="primary"
            icon="Printer"
            plain
            :disabled="disDelete || disPrint"
            @click="handleSalesSlip"
            >批量打印签购单</el-button
          >
        </el-col>
        <right-toolbar @queryTable="getList" v-model:showSearch="showSearch">
          <el-tooltip
            class="item"
            effect="dark"
            :content="'自定义列表'"
            placement="top"
          >
            <el-button circle icon="Menu" @click="handleTable()" />
          </el-tooltip>
        </right-toolbar>
      </el-row>

      <el-row :gutter="10" class="mb4">
        <el-col :span="1.5" class="text-2xl text-red-600"
          >{{ errA8Msg }}
        </el-col>
      </el-row>
      <el-table
        class="sticky-table"
        v-loading="loading"
        :data="tableList"
        row-key="id"
        stripe
        border
        :scrollbar-always-on="true"
        @selection-change="handleSelectionChange"
        :cell-class-name="cellClass"
        @row-dblclick="
          row => {
            goTo('/sales/indent/salesOrderDetails', {
              salesOrderId: row.id
            })
          }
        "
      >
        <el-table-column
          type="selection"
          width="40"
          align="center"
          fixed="left"
        />
        <!-- <el-table-column
          prop="contractOrderNumber"
          label="合同(订单)编号"
          width="160"
        >
        </el-table-column>
        <el-table-column prop="customerName" label="关联客户" min-width="200">
        </el-table-column>
        <el-table-column
          prop="price"
          label="订单总金额"
          width="130"
          align="center"
        >
          <template #default="scope">
            <span v-if="scope.row.price">{{ scope.row.price }}</span
            ><span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="repaymentPrice"
          label="已回款金额"
          width="130"
          align="center"
        >
          <template #default="scope">
            <span v-if="scope.row.repaymentPrice"
              >{{ scope.row.repaymentPrice }}</span
            ><span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="invoiceStatus"
          show-overflow-tooltip
          label="发票状态"
          width="130"
        >
          <template #default="scope">
            <div>
              <el-tooltip
                :disabled="!scope.row.invoiceMsg"
                effect="dark"
                :content="scope.row.invoiceMsg"
                placement="top"
              >
                <dict-drop
                  :options="order_invoice_status"
                  :value="scope.row.invoiceStatus"
                />
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="invoicePrice"
          label="已开票金额"
          width="130"
          align="center"
        >
          <template #default="scope">
            <span v-if="scope.row.invoicePrice"
              >{{ scope.row.invoicePrice }}</span
            ><span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="130" align="center">
          <template #default="scope">
            <div>
              <dict-drop :options="order_status" :value="scope.row.status" />
              <span
                class="text-12px text-#999999"
                v-if="scope.row.approvalStatus"
                >({{ scope.row.approvalStatus }})</span
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="transactionName" label="销售人员" width="100" />
        <el-table-column prop="customerCreditCode" label="税号" width="200">
        </el-table-column>
        <el-table-column prop="receiptsDate" label="单据日期" width="110">
        </el-table-column>
        <el-table-column
          prop="businessType"
          label="业务板块"
          width="130"
          align="center"
        >
          <template #default="scope">
            <dict-drop
              :options="order_business_type"
              :value="scope.row.businessType"
            ></dict-drop>
          </template>
        </el-table-column>
        <el-table-column
          prop="synchronousMsg"
          show-overflow-tooltip
          label="同步情况"
          width="130"
        >
        </el-table-column> -->
        <el-table-column
          v-for="(item, index) in tableCol.filter(item => item.show)"
          :key="index"
          v-bind="item"
        >
          <template #default="scope">
            <div v-if="item.tooltip">
              <el-tooltip
                :disabled="!scope.row.invoiceMsg"
                effect="dark"
                :content="item.tooltip(scope.row)"
                placement="top"
              >
                {{ item.tooltipVal(scope.row) }}
              </el-tooltip>
            </div>
            <div v-if="scope.column.label == '状态'">
              <dict-drop :options="order_status" :value="scope.row.status" />
              <span
                class="text-12px text-#999999"
                v-if="scope.row.approvalStatus"
                >({{ scope.row.approvalStatus }})</span
              >
            </div>
            <div v-if="scope.column.label == 'CRM同步情况'">
              <div>{{ scope.row.crmMsg }}</div>
              <el-button
                plain
                size="small"
                type="primary"
                icon="Sort"
                :disabled="
                  !(
                    scope.row.crmStatus != 1 && scope.row.synchronousStatus == 2
                  )
                "
                style="padding-left: 0.5rem"
                @click="synchronousCRMFn(scope.row)"
                >同步CRM</el-button
              >
            </div>
            <div v-if="scope.column.label == '诺诺同步情况'">
              <div>{{ scope.row.nuonuoMsg }}</div>
              <el-button
                plain
                size="small"
                type="primary"
                icon="Sort"
                :disabled="
                  !(
                    (!scope.row.nuonuoStatus || scope.row.nuonuoStatus == 0) &&
                    scope.row.synchronousStatus == 2
                  )
                "
                style="padding-left: 0.5rem"
                @click="synchronousNuonuoFn(scope.row)"
                >同步诺诺</el-button
              >
            </div>
            <div v-if="scope.column.label == '诺企服同步情况'">
              <div>{{ scope.row.aisinoMsg }}</div>
              <el-button
                plain
                size="small"
                type="primary"
                icon="Sort"
                :disabled="
                  !(
                    (!scope.row.aisinoStatus || scope.row.aisinoStatus == 0) &&
                    scope.row.synchronousStatus == 2
                  )
                "
                style="padding-left: 0.5rem"
                @click="synchronousAisinoFn(scope.row)"
                >同步诺企服</el-button
              >
            </div>
            <div v-if="scope.column.label == 'A8同步情况'">
              <div>{{ scope.row.synchronousMsg }}</div>
              <el-button
                plain
                size="small"
                type="primary"
                icon="Sort"
                :disabled="
                  scope.row.status == '4' ||
                  scope.row.synchronousStatus == '2' ||
                  scope.row.approvalStatus !== '审批通过'
                "
                style="padding-left: 0.5rem; padding-right: 0.5rem"
                @click="synchronousFn(scope.row)"
                >同步A8</el-button
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="120"
          fixed="right"
          class-name="small-padding"
        >
          <template #header>
            <div>操作</div>
          </template>
          <template #default="scope">
            <el-dropdown type="primary" class="align-middle">
              <el-button link type="primary"
                >更多 <el-icon class="el-icon--right"> <arrow-down /> </el-icon
              ></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    :disabled="scope.row.status !== '5'"
                    @click="handleSalesSlip(scope.row)"
                    >签购单</el-dropdown-item
                  >
                  <el-dropdown-item
                    :disabled="scope.row.status !== '5'"
                    @click="copySalesOrderCopy(scope.row)"
                    >再来一单</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <!-- <el-button
              plain
              size="small"
              type="primary"
              icon="CircleCheckFilled"
              @click="handleContinue(scope.row)"
              style="padding-left: 0.5rem; padding-right: 0.5rem"
              >跟进</el-button
            >
            <el-button
              plain
              size="small"
              type="success"
              icon="RemoveFilled"
              style="padding-left: 0.5rem; padding-right: 0.5rem"
              @click="
                goTo('/financial/repaymentDetails', {
                  salesOrderId: scope.row.id
                })
              "
              >回款</el-button
            > -->
            <!-- <el-button
              plain
              size="small"
              type="primary"
              icon="Postcard"
              :disabled="
                scope.row.status == '4' ||
                scope.row.synchronousStatus !== '2' ||
                scope.row.approvalStatus !== '审批通过' ||
                scope.row.invoiceStatus == '1' ||
                scope.row.invoiceStatus == '3'
              "
              v-hasPermi="['salesOrder:makeOutInvoice']"
              style="padding-left: 0.5rem; padding-right: 0.5rem"
              @click="invoiceFn(scope.row)"
              >开票</el-button
            > -->
            <!-- 
             -->
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 跟进弹窗 -->
      <FollowUp
        :dialogParam="followUpParam"
        @ok="saveFn"
        @close="followUpParam.isVisible = false"
      ></FollowUp>

      <!-- 客户弹出框下拉框 -->
      <SelectCustomer
        v-if="dialogParamA.isDialog"
        :dialog-param="dialogParamA"
        @ok="selectCustomerData"
        @close="
          val => {
            dialogParamA.isDialog = false
          }
        "
      ></SelectCustomer>

      <!-- 关闭订单弹窗 -->
      <el-dialog
        :title="stopDialog.title"
        v-model="stopDialog.open"
        width="40%"
        :close-on-click-modal="false"
      >
        <el-form
          ref="formRules"
          :model="formStopData"
          :rules="formStopRules"
          label-width="120px"
          status-icon
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="关闭原因" prop="stopReason">
                <el-input
                  v-model="formStopData.stopReason"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入关闭原因"
                  maxlength="300"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="stopDialog.open = false">取 消</el-button>
            <el-button type="primary" @click="handleStopSubmit">保存</el-button>
          </span></template
        >
      </el-dialog>

      <!-- 人员弹出框下拉框 -->
      <SelectDialog
        :dialog-param="dialogParam"
        @ok="selectDialogData"
        @close="
          val => {
            dialogParam.isDialog = false
          }
        "
      ></SelectDialog>

      <!-- 红字开票 -->
      <InvoiceDialog
        v-model="redInvoiceParam.open"
        :dialogData="redInvoiceParam"
        @getData="redDialogFn"
      />

      <!-- 导入弹窗 -->
      <el-dialog
        :title="uploadDia.title"
        v-model="uploadDia.open"
        width="400px"
        append-to-body
        @close="closeUpload"
        :close-on-click-modal="false"
      >
        <el-upload
          v-loading="uploadLoading"
          action="#"
          :before-upload="beforeAvatarUpload"
          :http-request="requestFile"
          accept=" .xls, .xlsx"
          :show-file-list="false"
          drag
        >
          <el-icon class="el-icon--upload">
            <upload-filled />
          </el-icon>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <template #tip>
            <div>
              <div class="el-upload__tip text-center">
                <span class="text-red">仅允许导入蓝字订单</span>
                <el-link
                  type="primary"
                  :underline="false"
                  style="font-size: 12px; vertical-align: baseline"
                  @click="downUrl"
                  >下载模板
                </el-link>
              </div>
              <div v-if="uploadDia.message" style="white-space: pre-line">
                导入结果：{{ uploadDia.message }}
              </div>
            </div>
          </template>
        </el-upload>
        <template #footer>
          <div class="dialog-footer">
            <!-- <el-button type="primary" @click="submitFileForm">确 定</el-button> -->
            <el-button @click="closeUpload">取 消</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 自定义订单列表弹窗 -->
      <DiaFixTable
        v-model="diaTable.open"
        :dialogParam="diaTable"
        @ok="diaTableFn"
      />

      <!-- 自动审核配置弹窗 -->
      <ReviewConfig v-model="reviewParams.open" />

      <!-- 权限弹窗 -->
      <el-dialog
        title="分配"
        v-model="showAuthority"
        @open="getUserList"
        width="70%"
      >
        <el-form
          :model="queryAuthForm"
          ref="queryRef"
          :inline="true"
          v-show="showSearch"
          label-width="0"
        >
          <el-form-item label="" prop="userName">
            <el-input
              v-model="queryAuthForm.userName"
              placeholder="请输入登录账号"
              clearable
              style="width: 130px"
              @change="getUserList"
            />
          </el-form-item>
          <el-form-item label="" prop="nickName">
            <el-input
              v-model="queryAuthForm.nickName"
              placeholder="请输入用户姓名"
              clearable
              style="width: 130px"
              @change="getUserList"
            />
          </el-form-item>
          <el-form-item label="" prop="orderAuthorityType">
            <el-select
              style="width: 130px"
              clearable
              v-model="queryAuthForm.orderAuthorityType"
              placeholder="请选择权限类型"
            >
              <el-option
                v-for="item in order_authority_type"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="getUserList"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetAuthForm">重置</el-button>
          </el-form-item>
        </el-form>
        <el-table v-loading="loadingAuth" :data="userList" border>
          <el-table-column
            label="登录账号"
            align="center"
            key="userName"
            prop="userName"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="用户姓名"
            align="center"
            key="nickName"
            prop="nickName"
            :show-overflow-tooltip="true"
          />

          <el-table-column
            label="权限更新时间"
            align="center"
            prop="authorityUpdateTime"
          >
            <template #default="scope">
              <span>{{
                parseTime(scope.row.authorityUpdateTime, '{y}-{m}-{d}')
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="权限更新人"
            align="center"
            prop="authorityUpdateUserName"
          />
          <el-table-column
            label="权限类型"
            align="center"
            prop="orderAuthorityType"
          >
            <template #default="scope">
              <dict-drop
                :options="order_authority_type"
                :value="scope.row.orderAuthorityType"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="80">
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                icon="User"
                @click="handleSetIdentity(scope.row)"
                >分配</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="sum > 0"
          :total="sum"
          v-model:page="queryAuthForm.pageNum"
          v-model:limit="queryAuthForm.pageSize"
          @pagination="getUserList"
        />
      </el-dialog>

      <el-drawer
        v-model="drawer"
        title="配置"
        direction="rtl"
        :before-close="handleDrawerClose"
        destroy-on-close
        size="70%"
      >
        <Identity :userInfo="userInfo" />
      </el-drawer>

      <!-- 订单权限分配 -->
      <el-dialog
        :title="'分配'"
        v-model="allocation"
        width="40%"
        :close-on-click-modal="false"
      >
        <el-form
          ref="formAllocationRef"
          :model="formAllocation"
          :rules="formAllocationRules"
          label-width="120px"
          status-icon
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="权限类型" prop="orderAuthorityType">
                <el-select
                  class="w-full"
                  v-model="formAllocation.orderAuthorityType"
                  placeholder="请选择权限类型"
                >
                  <el-option
                    v-for="item in order_authority_type"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="allocation = false">取 消</el-button>
            <el-button type="primary" @click="handleAllocation">保存</el-button>
          </span></template
        >
      </el-dialog>

      <!-- 导出列表框 -->
      <el-dialog
        title="导出"
        v-model="showExportTask"
        width="600"
        :close-on-click-modal="false"
        @close="closeExport"
      >
        <el-row
          v-for="item in downloadTaskList"
          :key="item.fileId"
          class="my-20px taskList"
        >
          <el-col :span="8">{{ item.createTime }}</el-col>
          <el-col :span="3">{{
            item.state == '1' ? '下载完成' : '下载中'
          }}</el-col>
          <el-col :span="4" v-if="item.state === '1' && item.url">
            <a :href="item.url" class="color-#4a9eff" download>下载</a></el-col
          >
        </el-row>
        <template #footer>
          <div>
            <el-button type="primary" @click="handleExport">新建导出</el-button>
            <el-button @click="closeExport">关闭</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 签购单 -->
      <SalesSlip v-if="salesSlipDia.open" :dialogParam="salesSlipDia" />
    </div>
  </div>
</template>
<script setup name="SalesOrder">
import { reactive, toRefs, ref, toRaw } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
  order_status, //订单状态
  order_biz_type, //业务类型
  order_source, //订单来源
  order_invoice_status, //发票状态
  order_synchronous_status, //同步状态
  invoice_manage_type, //发票类型
  crm_status, //crm状态
  nuonuo_status, //诺诺、爱企服状态
  order_authority_type, //订单权限类型
  companyOption, //所属公司
  businessTypeOption, //业务类型树
  projectOptionsLimitEnt, //项目数据
  queryProjectLimitEnt, //检索项目
  contractOptionsLimitEnt, //合同数据
  queryContractLimitEnt, //检索合同数据
  SALESORDERTABLE //订单列表配置
} from '@/hooks/dict/order'
import {
  listSalesOrder,
  stopSalesOrder,
  getSalesOrder,
  setSalesOrder,
  getToA8Fail,
  salesOrderCopy,
  synchronousA8,
  synchronousCRM,
  synchronousNuonuo,
  synchronousAisino,
  blueMakeOutInvoice,
  importOrderData,
  exportOrder
} from '@/api/indentManage/indent'
import { listUser, orderAuthorityType } from '@/api/system/user'
import { getExportList } from '@/api/rsgl/ygda'
import { treeselect } from '@/api/rsgl/zzjg'
import FollowUp from '@/businessComponents/FollowUp'
import { getPricipalId, initTable } from '@/utils/commo'
import ReviewConfig from './modules/reviewConfig'
import useCommonStore from '@/store/modules/common'
import { format, startOfMonth, endOfMonth } from 'date-fns'
import Identity from './modules/Identity'
import SalesSlip from './modules/salesSlip'
import { maxDecimals } from '@/utils/validate'

const commonStore = useCommonStore()

const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()

const now = new Date()

const userOption = ref({ transactionId: [] })
const deptIdOption = ref([])
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    number: undefined,
    status: undefined,
    receiptsDates: [
      format(startOfMonth(now), 'yyyy-MM-dd'),
      format(endOfMonth(now), 'yyyy-MM-dd')
    ],
    bizType: undefined,
    source: undefined,
    customerId: undefined,
    price: undefined,
    projectId: undefined,
    invoiceStatus: undefined,
    contractId: undefined,
    deptId: userStore.userInfo.orgId,
    businessType: undefined
  },
  ids: [],
  selectArr: [],
  total: 0,
  option: {
    labelWidth: '10',
    menuSpan: 7,
    submitBtn: false,
    menuPosition: 'left',
    // gutter: 30,
    emptyBtn: false,
    column: [
      {
        prop: 'contractOrderNumber',
        span: 3,
        placeholder: '订单号',
        type: 'input'
      },
      {
        // label: '性别',
        span: 3,
        prop: 'status',
        placeholder: '状态',
        type: 'select',
        dicData: order_status
      },
      {
        prop: 'receiptsDates',
        type: 'daterange',
        span: 6,
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        startPlaceholder: '单据开始时间',
        endPlaceholder: '单据结束时间'
      },
      {
        prop: 'deptId',
        span: 3,
        placeholder: '所属公司',
        type: 'tree',
        defaultExpandAll: true,
        disabled: userStore.userInfo.orgId != 484,
        props: {
          value: 'id', //   value: 'deptId',
          label: 'label' //   label: 'deptName'
        },
        dicData: companyOption
      },
      {
        span: 4,
        prop: 'customerName',
        placeholder: '客户名称',
        type: 'input'
      },
      {
        span: 4,
        prop: 'customerCreditCode',
        placeholder: '税号',
        type: 'input'
      },
      {
        prop: '_transactionId',
        span: 3,
        placeholder: '所属人员',
        type: 'select',
        clearable: false,
        props: {
          value: 'uuid'
        },
        popperClass: 'className',
        dicData: computed(() => {
          return userOption.value['transactionId']
        }),
        multiple: false,
        click: ({ value, column }) => {
          dialogParam.value.type = 'transactionId'
          dialogParam.value.title = '请选择人员'
          dialogParam.value.isDialog = true
          dialogParam.value.multiple = false
          dialogParam.value.nodeKey = 'uuid'
          dialogParam.value.apiParams = { deptId: 100 }
          dialogParam.value.defaultCheckedKeys = [
            queryParams.value._transactionId
          ]
          dialogParam.value.dataType = 'person'
        }
      },
      {
        span: 3,
        prop: 'invoiceStatus',
        placeholder: '发票状态',
        type: 'select',
        dicData: order_invoice_status
      },
      {
        span: 3,
        prop: 'synchronousStatus',
        placeholder: 'A8同步状态',
        type: 'select',
        dicData: order_synchronous_status
      },
      {
        prop: 'approvalTime',
        type: 'daterange',
        span: 5,
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        startPlaceholder: '最新审核开始时间',
        endPlaceholder: '最新审核结束时间'
      },
      {
        span: 3,
        prop: 'productName',
        placeholder: '产品名称',
        type: 'input'
      }
    ]
  },
  searchOption: {
    submitBtn: false,
    emptyBtn: false,
    menuPosition: 'left',
    labelWidth: '120',
    column: [
      {
        label: '订单查询',
        prop: 'number',
        span: 12,
        placeholder: '订单号',
        type: 'input'
      },
      {
        label: '状态',
        span: 12,
        prop: 'status',
        placeholder: '状态',
        type: 'select',
        dicData: order_status
      },
      {
        label: '单据时间',
        prop: 'receiptsDates',
        type: 'daterange',
        span: 12,
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        startPlaceholder: '单据开始时间',
        endPlaceholder: '单据结束时间'
      },
      {
        label: '同步时间',
        prop: 'synchronousTime',
        type: 'daterange',
        span: 12,
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        startPlaceholder: '同步开始时间',
        endPlaceholder: '同步结束时间'
      },
      {
        label: '业务类型',
        span: 12,
        prop: 'bizType',
        placeholder: '业务类型',
        type: 'select',
        dicData: order_biz_type
      },
      // {
      //   label: '付款时间',
      //   prop: 'payDates',
      //   type: 'daterange',
      //   span: 12,
      //   format: 'YYYY-MM-DD',
      //   valueFormat: 'YYYY-MM-DD',
      //   startPlaceholder: '付款开始时间',
      //   endPlaceholder: '付款结束时间'
      // },
      {
        label: '订单来源 ',
        span: 12,
        prop: 'source',
        placeholder: '订单来源',
        type: 'select',
        dicData: order_source
      },
      {
        label: '客户名称',
        span: 12,
        prop: 'customerName',
        placeholder: '客户名称'
      },
      {
        label: '订单金额',
        span: 12,
        prop: 'price',
        placeholder: '订单金额',
        type: 'number',
        controls: false,
        rules: [
          {
            validator: (rule, value, callback) => {
              maxDecimals(rule, value, callback, 6)
            }
          }
        ]
        // dicData: order_price
      },
      {
        label: '关联项目',
        span: 12,
        prop: 'projectId',
        placeholder: '关联项目'
      },
      {
        label: '发票状态',
        span: 12,
        prop: 'invoiceStatus',
        placeholder: '发票状态',
        type: 'radio',
        dicData: order_invoice_status
      },
      {
        label: '关联合同',
        span: 12,
        prop: 'contractId',
        placeholder: '关联合同'
      },

      {
        label: '所属公司',
        prop: 'deptId',
        span: 12,
        placeholder: '所属公司',
        defaultExpandAll: true,
        type: 'tree',
        props: {
          value: 'id', //   value: 'deptId',
          label: 'label' //   label: 'deptName'
        },
        dicData: companyOption,
        change: val => {
          queryParams.value.deptId = val.value
          getDeptTree()
        }
      },
      {
        label: '所属部门',
        prop: 'transactionDept',
        span: 12,
        placeholder: '所属部门',
        type: 'tree',
        defaultExpandAll: true,
        props: {
          value: 'id', //   value: 'deptId',
          label: 'label' //   label: 'deptName'
        },
        dicData: deptIdOption
      },
      {
        label: '业务板块',
        span: 12,
        prop: 'businessType',
        placeholder: '业务板块',
        type: 'tree',
        dicData: businessTypeOption
      },
      {
        label: '发票类型',
        span: 12,
        prop: 'invoiceType',
        placeholder: '发票类型',
        type: 'tree',
        dicData: invoice_manage_type
      },
      {
        label: '所属人员',
        prop: '_transactionId',
        span: 12,
        placeholder: '所属人员',
        type: 'select',
        clearable: false,
        props: {
          value: 'uuid'
        },
        popperClass: 'className',
        dicData: computed(() => {
          return userOption.value['transactionId']
        }),
        multiple: false,
        click: ({ value, column }) => {
          dialogParam.value.type = 'transactionId'
          dialogParam.value.title = '请选择人员'
          dialogParam.value.isDialog = true
          dialogParam.value.multiple = false
          dialogParam.value.nodeKey = 'uuid'
          dialogParam.value.apiParams = { deptId: 100 }
          dialogParam.value.defaultCheckedKeys = [
            queryParams.value._transactionId
          ]
          dialogParam.value.dataType = 'person'
        }
      },
      {
        label: 'crm同步状态',
        span: 12,
        prop: 'crmStatus',
        placeholder: 'crm同步状态',
        type: 'tree',
        dicData: crm_status
      },
      {
        label: '诺诺同步状态',
        span: 12,
        prop: 'nuonuoStatus',
        placeholder: '诺诺同步状态',
        type: 'tree',
        dicData: nuonuo_status
      },
      {
        label: '爱企服同步状态',
        span: 12,
        prop: 'aisinoStatus',
        placeholder: '爱企服同步状态',
        type: 'tree',
        dicData: nuonuo_status
      },
      {
        label: '订单查询',
        prop: 'numberText',
        span: 24,
        placeholder: '请输入订单编号，回车空格，,分割例如：123,456,789',
        type: 'textarea',
        autosize: true
        // minRows: 3
      }
    ]
  },
  showSearch: true,
  searchDrawer: false /* 高级检索框 */,
  disUpdate: true /* 编辑按钮是否可编辑 */,
  disDelete: true /* 关闭按钮是否可编辑 */,
  loading: false,
  tableList: [],
  followUpParam: {}, // 跟进弹窗配置
  dialogParam: {},
  dialogParamA: {}, //客户弹窗配置
  customerOption: {}, //客户选择下拉
  stopDialog: {
    title: '关闭订单',
    open: false
  },
  stopBtn: false, //关闭订单按钮权限
  formStopData: {
    id: '',
    status: '',
    stopReason: undefined
  }, //关闭订单数据
  formStopRules: {
    stopReason: [
      {
        required: true,
        message: '请输入关闭原因',
        trigger: 'blur'
      }
    ]
  } //关闭订单效验
})
const {
  queryParams,
  ids,
  selectArr,
  total,
  option,
  searchOption,
  showSearch,
  searchDrawer,
  disUpdate,
  disDelete,
  loading,
  tableList,
  followUpParam,
  dialogParam,
  dialogParamA,
  customerOption,
  stopDialog,
  stopBtn,
  formStopData,
  formStopRules
} = toRefs(data)
watch(
  [() => route.query.salesOrderData],
  async () => {
    if (route.query.salesOrderData) {
      queryParams.value = JSON.parse(route.query.salesOrderData)
      getList()
    }
  },
  {
    immediate: true
  }
)

const tableCol = ref(SALESORDERTABLE)
// 自定义列表弹窗参数
const diaTable = ref({
  open: false,
  tableName: 'salesOrderTable', //唯一值防止与其他列表混合
  tableCol: tableCol.value,
  initCol: SALESORDERTABLE
})

// 自定义列表
const handleTable = () => {
  diaTable.value.open = true
  diaTable.value.tableCol = tableCol.value
}
const cellClass = ({ row, column }) => {
  // console.log('row', row)
  // console.log('column', column)
}
// 获取列表配置
const diaTableFn = value => {
  tableCol.value = value
}

// 初始化
async function init() {
  // 初始化列表配置
  tableCol.value = initTable(diaTable.value.tableName, SALESORDERTABLE)
  // }
  // 归属部门
  getList()
}
// 获取部门树
const getDeptTree = () => {
  if (!queryParams.value.deptId) return
  queryParams.value.transactionDept = ''
  let data = { deptId: queryParams.value.deptId }
  treeselect(data).then(res => {
    deptIdOption.value = res.data
  })
}
getDeptTree()
// 提交
function handleSubmit() {
  console.log('提交--》', queryParams.value)
}
// 重置
function handleEmpty(formEl) {
  console.log('queryParams.value1==>', toRaw(queryParams.value))
  proxy.resetForm('searchForm')
  proxy.resetForm('seniorSearchForm')
  // proxy.$refs.searchForm.resetForm()
  getList()
}
// 高级检索
function handleSearch() {
  searchDrawer.value = true
}

// 获取数据列表
function getList() {
  loading.value = true
  // 所属人员
  queryParams.value.transactionId = getPricipalId(
    userOption.value['transactionId'],
    queryParams.value._transactionId || ''
  ).toString()
  listSalesOrder(queryParams.value).then(res => {
    loading.value = false
    tableList.value = res.rows
    total.value = res.total
    getA8Msg()
  })
  console.log('获取数据')
}
const errA8Msg = ref('')
// 获取错误提示信息
function getA8Msg() {
  queryParams.value.transactionId = getPricipalId(
    userOption.value['transactionId'],
    queryParams.value._transactionId || ''
  ).toString()
  getToA8Fail(queryParams.value).then(res => {
    errA8Msg.value = res.data
  })
}
// 打印签购单控制
const disPrint = ref(true)
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  selectArr.value = selection
  disUpdate.value = selection.length != 1
  disDelete.value = !selection.length
  stopBtn.value = selectArr.value.some(e => {
    //判断是否管理员、是否本人、是否4
    let isControl = false
    let isGly = userStore.roles.some(item => item == 'xsddgly') //判断是否订单管理员
    // console.log('isGly==>', isGly)
    if (e.status == '4') {
      return true //判断是否已经终止
    }
    isControl = e.createBy == userStore.userInfo.userName
    return isGly ? false : !isControl
  })
  disPrint.value = selectArr.value.some(e => {
    return e.status !== '5'
  })
}
// 双击行
function dbclickRow(row, column, event) {
  goTo('/sales/indent/salesOrderDetails', {
    salesOrderId: row.id
  })
}
// 同步到A8
function synchronousFn(row) {
  synchronousA8(row.id).then(() => {
    proxy.$modal.msgSuccess('同步成功')
    getList()
  })
}
// 同步到CRM
function synchronousCRMFn(row) {
  synchronousCRM(row.id).then(() => {
    proxy.$modal.msgSuccess('同步成功')
    getList()
  })
}
// 同步到诺诺
function synchronousNuonuoFn(row) {
  synchronousNuonuo(row.id).then(() => {
    proxy.$modal.msgSuccess('同步成功')
    getList()
  })
}
// 同步到诺企服
function synchronousAisinoFn(row) {
  synchronousAisino(row.id).then(() => {
    proxy.$modal.msgSuccess('同步成功')
    getList()
  })
}
function goTo(url, data) {
  router.push({ path: url, query: data })
}
function handleAdd() {
  goTo('/sales/indent/salesOrderForm', {})
}
function handleDownload() {}
function handleUpdate() {
  goTo('/sales/indent/editSalesOrder', { salesOrderId: ids.value[0] })
}

//打开跟进弹窗
function handleContinue(row) {
  console.log('跟进==》', followUpParam.value)
  /***订单模块 */
  // console.log('row==>', row)
  followUpParam.value.isVisible = true
  followUpParam.value.tableName = 'ord_order'
  followUpParam.value.businessId = row.id
  followUpParam.value.customer = row.customerName
  followUpParam.value.orderName = row.title
}

/**
 * 客户选择选择
 * @param keyName
 */
function selectCustomerFn(keyName) {
  switch (keyName) {
    case 'customerId':
      dialogParamA.value.type = keyName
      dialogParamA.value.tabVal = 'customer'
      dialogParamA.value.title = '客户选择'
      dialogParamA.value.isDialog = true
      dialogParamA.value.multiple = false
      dialogParamA.value.nodeKey = 'id'
      // dialogParamA.value.defaultCheckedKeys = formData.value[keyName]
      // dialogParamA.value.defaultCheckedLabel = formData.value['customerName']
      dialogParamA.value.dataType = 'person'
      break
  }
}

// 客户选择选择确定
const selectCustomerData = val => {
  switch (val.type) {
    case 'customerId':
      customerOption.value.customerId = val.selectData
      queryParams.value.customerId = val.defaultCheckedKeys
        ? val.defaultCheckedKeys.toString()
        : null
      break
  }
}

// 确认跟进
function saveFn() {}
// 关闭订单
function handleStop() {
  proxy.resetForm('formRules')
  stopDialog.value.open = true
  formStopData.value.id = ids.value[0]
  formStopData.value.status = '4'
}

// 保存关闭订单
function handleStopSubmit() {
  proxy.$refs.formRules.validate((valid, msg) => {
    if (valid) {
      stopSalesOrder(formStopData.value).then(res => {
        proxy.$modal.msgSuccess('关闭成功')
        stopDialog.value.open = false
        getList()
      })
    }
  })
}

const reviewParams = ref({
  open: false
})
// 自动审核配置按钮
const handleReview = () => {
  reviewParams.value.open = true
}

const showAuthority = ref(false)
const drawer = ref(false)
const loadingAuth = ref(false)
const userList = ref([])
const queryAuthForm = ref({
  pageSize: 10,
  pageNum: 1
})
const sum = ref(0)
function getUserList() {
  const params = { ...queryAuthForm.value, deptId: userStore.userInfo.orgId }
  listUser(params).then(res => {
    userList.value = res.rows
    sum.value = res.total
  })
}

function resetAuthForm() {
  queryAuthForm.value = {
    pageSize: 10,
    pageNum: 1
  }
  getUserList()
}

function authoritySetting() {
  showAuthority.value = true
}
const userInfo = ref()
function handleSetIdentity(row) {
  userInfo.value = row
  // drawer.value = true

  // console.log('row==>', row)
  proxy.resetForm('formAllocationRef')
  allocation.value = true
  formAllocation.value.orderAuthorityType = row.orderAuthorityType
  formAllocation.value.userId = row.userId
}

function handleDrawerClose() {
  drawer.value = false
}
const allocation = ref(false)
const formAllocation = ref({ orderAuthorityType: '3' })
const formAllocationRules = ref({
  orderAuthorityType: [
    {
      required: true,
      message: '请选择权限类型',
      trigger: 'change'
    }
  ]
})
const handleAllocation = async () => {
  proxy.$refs.formAllocationRef.validate(async (valid, msg) => {
    if (valid) {
      let res = await orderAuthorityType(formAllocation.value)
      if (res.code !== 200) return
      proxy.$message.success('配置成功')
      getUserList()
      if (formAllocation.value.orderAuthorityType == '3') {
        drawer.value = true
      }
      allocation.value = false
    }
  })
}

// 导入弹窗
const uploadDia = ref({
  title: '导入订单',
  open: false,
  message: ''
})
// 获取培训产业模板链接/file/系统模板文件/培训产业登记表V1_20230728155654A001.xls
const downUrl = async function downUrl() {
  const url = await commonStore.getUploadTemplateDown('order_imp_template')
  // console.info('url', url)
  window.open(url, '_blank')
}
/**导入数据 限制条件
 *
 * @param {*} rawFile
 */
const uploadLoading = ref(false)
function beforeAvatarUpload(rawFile) {
  const ext = rawFile.name.substring(rawFile.name.lastIndexOf('.'))
  const allowType = ['.xls', '.xlsx'].indexOf(ext) > -1
  const isLt2M = rawFile.size / 1024 / 1024 < 200

  if (!allowType) {
    proxy.$message.error('上传文件只能是doc、docx、pdf格式!')
  } else if (!isLt2M) {
    proxy.$message.error('上传文件大小不能超过 200MB!')
  }
  return allowType && isLt2M
}
// 上传文件
async function requestFile(params) {
  uploadLoading.value = true
  let uploadData = new FormData()
  uploadData.append('file', params.file)
  // uploadData.append('type', formData.value.businessType)
  try {
    let res = await importOrderData(uploadData)
    uploadLoading.value = false
    if (res.code === 200) {
      proxy.$modal.msgSuccess('导入成功')
      uploadDia.value.message = '导入成功!'
      getList()
    }
  } catch (error) {
    uploadLoading.value = false
    console.log('error===>', error)
    uploadDia.value.message = error.toString().replace('Error:', '')
  }
}
// 关闭导入弹窗
function closeUpload() {
  uploadDia.value.open = false
  uploadDia.value.message = ''
}

/* 人员确认 */
const selectDialogData = val => {
  switch (val.type) {
    case 'transactionId':
      userOption.value.transactionId = val.selectData
      // queryOption.value.column[2].dicData = val.selectData
      queryParams.value._transactionId = val.defaultCheckedKeys.toString()
      break
  }
}

const showExportTask = ref(false)
// 导出文件
function exportFile(query) {
  showExportTask.value = true
  exportList()
  // downLoadByUrl('/ord/supervision/export', queryParams.value, {
  //   fileName: '合同监督的导出'
  // })
}
const handleExport = () => {
  queryParams.value.transactionId = getPricipalId(
    userOption.value['transactionId'],
    queryParams.value._transactionId
  ).toString()
  let query = {
    loginUserId: userStore.user.userId,
    type: 'xsdd',
    ...queryParams.value
  }
  exportOrder(query).then(res => {
    proxy.$modal.msgSuccess('正在导出')
    // exportList()
    animloop()
  })
}

let rafId = null
let lastTime = null
function animloop(currentTime) {
  cancelAnimationFrame(rafId)
  rafId = requestAnimationFrame(animloop)
  // console.log(`现在${currentTime}===${lastTime}`)
  // console.log(`现在${rafId}===`)
  // 每5秒执行一次
  if (!lastTime || currentTime - lastTime >= 5000) {
    // 执行你的逻辑
    exportList()
    // 更新上一次执行的时间
    lastTime = currentTime
  }
  // 五分钟后取消
  if (currentTime - lastTime >= 300000) {
    lastTime = currentTime
    cancelAnimationFrame(rafId)
  }
}

const downloadTaskList = ref([])
const exportList = () => {
  getExportList({
    createId: userStore.user.userId,
    type: 'xsdd'
  }).then(res => {
    downloadTaskList.value = res.data
  })
}
const closeExport = () => {
  console.log('关闭')
  showExportTask.value = false
  cancelAnimationFrame(rafId)
}

// 发票信息弹窗参数
const invoiceParam = ref({
  open: false
})
const redInvoiceParam = ref({
  open: false
})
// 点击开票按钮
const invoiceFn = async row => {
  // console.log('row==>', row.property)
  if (row.property == '0') {
    //订单蓝字
    let res = await getSalesOrder(row.id)
    if (res.code !== 200) return
    invoiceParam.value.open = true
    invoiceParam.value.formData = res.data
  } else if (row.property == '1') {
    //订单红字
    redInvoiceParam.value.open = true
    redInvoiceParam.value.isSelection = false
    redInvoiceParam.value.dialogType = '开票'
    redInvoiceParam.value.query = {
      orderId: row.oppositeId
    }
  }
}
// 开票
const invoicingFn = async val => {
  console.log('开票val===>', val)
  let res = await setSalesOrder(val)
  if (res.code !== 200) return
  console.log('保存===>', res.data)
  let resOutInvoice = await blueMakeOutInvoice(res.data.id)
  if (resOutInvoice.code !== 200) return
  proxy.$modal.msgSuccess('提交成功')
  getList()
}
// 关闭红单开票弹窗时
const redDialogFn = val => {
  console.log('关闭红单==>', val)
  getList()
}

// 签购单
const salesSlipDia = ref({
  open: false,
  queryParam: {}
})
const handleSalesSlip = row => {
  const idArr = row.id || ids.value
  if (!idArr || idArr.length == 0) return
  console.log('idArr==>', idArr)
  salesSlipDia.value = {
    open: true,
    title: '签购单',
    queryParam: {
      orderId: idArr
    }
  }
}

// 再来一单
async function copySalesOrderCopy(row) {
  let res = await salesOrderCopy(row.id)
  if (res.code !== 200) return
  getList()
  console.log('res==>', res)
  goTo('/sales/indent/editSalesOrder', { salesOrderId: res.data.id })
}

init()
</script>
<style scoped lang="scss">
@import '@/assets/styles/myStyle.scss';
</style>
<style scoped lang="scss">
.search-drawer-retract {
  color: #999999;
}
</style>
